package cn.zebra.dev.sms.module.huaxin.controller;

import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.sms.huaxin.entity.MessageEntity;
import cn.zebra.dev.sms.huaxin.service.SysSmsService;
import cn.zebra.dev.sms.module.huaxin.vo.SmsSendContentVO;
import cn.zebra.dev.sys.module.sms.entity.SysSmsRecordEntity;
import cn.zebra.dev.sys.module.sms.service.SysSmsRecordService;
import io.swagger.annotations.ApiOperation;
import cn.zebra.dev.common.utils.StrUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

/**
 * @author runnable@sina.cn
 */
@RestController
@RequestMapping("/sms")
public class SmsController {

    @Autowired
    private SysSmsService smsService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SysSmsRecordService smsRecordService;

    @PostMapping("/sendContent")
    @ApiOperation("发送短信")
    public Result sendContent(@Valid @RequestBody SmsSendContentVO param) throws Exception {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        String key = param.getKey();
        String code = operations.get(key);
        if (StrUtils.isNotBlank(code)) {
            return Result.error("获取验证码过于频繁，请稍候重试!");
        }
        Integer minute = param.getMinute();
        MessageEntity messageEntity = smsService.sendSingleMessage(param.getPhone(), param.getContent());
        operations.set(key, param.getCode(), minute, TimeUnit.MINUTES);
        saveRecord(messageEntity);
        return Result.success(messageEntity.getReturnMessage());
    }

    @Async
    void saveRecord(MessageEntity messageEntity) {
        SysSmsRecordEntity recordEntity = new SysSmsRecordEntity();
        BeanUtils.copyProperties(messageEntity, recordEntity);
        smsRecordService.save(recordEntity);
    }
}
